from django.shortcuts import render, HttpResponse
from .forms import MessageBoardForm, RegisterForm, ArticleForm
from django.views.decorators.http import require_http_methods

# Create your views here.
@require_http_methods(['GET', 'POST'])
def index(request):
    # 这里的GET请求相当于浏览器向这个服务器请求index.html文件
    if request.method == 'GET':
        form = MessageBoardForm()
        return render(request, 'index.html', context={'form': form})
    else:
        # 这里的request.POST是用户通过表单提交上来的表单数据
        form = MessageBoardForm(request.POST)
        if form.is_valid():
            # 获取清除干净后的从表单中传来的数据title
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            email = form.cleaned_data.get('email')
            return HttpResponse(f'{title}, {content}, {email}')
        else:
            print(form.errors)
            return HttpResponse('表单验证失败')

@require_http_methods(['GET', 'POST'])
def register_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            return HttpResponse(telephone)
        else:
            print(form.errors.get_json_data())
            return HttpResponse("表单验证失败")

@require_http_methods(['GET', 'POST'])
def article_view(request):
    if request.method == 'GET':
        return render(request, 'article.html')
    else:
        form = ArticleForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            creat_time = form.cleaned_data.get('creat_time')
            return HttpResponse(f'{title}, {content}, {creat_time}')
        else:
            print(form.errors.get_json_data())
            return HttpResponse("表单验证失败")
